import FileSaver from 'file-saver'
import JSZip from 'jszip'

/**
 * 代码使用实例，在对应的页面中，直接用下面的代码替换原来的代码就可以了
  downImg (arr, imgNameList) {
      downAllImgAction(arr, imgNameList, this.downloadType, this)
    },
 */

/**
 * 创建时间：2021.11.18
 * 专门给批量下载图片使用的，如果在有新项目一定要用这个公共的方法，此方法包含了错误下载的内容，不会因为一个错误导致不能在使用
 * @param arr
 * @param imgNameList
 * @param downType
 * @param _this
 */
export const downAllImgAction = (arr, imgNameList, downType, _this) => {
  let blogTitle = '打包图片'
  switch (downType) {
    case 'horizontal':
      blogTitle = '横版打包图片'
      break
    case 'vertical':
      blogTitle = '竖版打包图片'
      break
  }
  let zip = new JSZip()
  let imgs = zip.folder(blogTitle)
  let baseList = []
  // 递归写法
  function preload (arr, index) {
    // console.log('当前图片：', arr)
    index = index || 0
    if (index >= arr.length) {
      return false
    }
    if (arr && arr.length > index) {
      let img = new Image()
      img.onload = function () {
        let image = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')

        image.onload = function () {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height

          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)

          let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
          _this.datasrc = url
          _this.downNowName = imgNameList[index] + '正在下载'
          console.log(_this.downNowName, '_this.downNowName')
          baseList.push(url.substring(22)) // 去掉base64编码前的 data:image/png;base64,
          if (baseList.length === arr.length && baseList.length > 0) {
            for (let k = 0; k < baseList.length; k++) {
              if (baseList[k] !== 'error') {
                imgs.file(imgNameList[k] + '.png', baseList[k], { base64: true })
              } else {
                _this.$Notice.warning({
                  title: '此图片生成失败，重新生成',
                  desc: imgNameList[k],
                  duration: 0
                })
              }
            }
            _this.downNowName = '打包压缩中...'
            zip.generateAsync({ type: 'blob' }).then(function (content) {
              // see FileSaver.js
              FileSaver.saveAs(content, blogTitle + '.zip')
              _this.downLoading = false
              _this.downImgModel = false
              console.log('结束时间：', _this.$common.xeUtils.toDateString(new Date()))
            })
          }
        }
        let ww = 'http://oss.lngov.top'
        let ak = arr[index].replace(ww, 'http://oss.tripln.top')
        console.log('当前src', ak)
        image.src = ak
        preload(arr, index + 1)
      }
      img.onerror = function (e) {
        console.log('图片生成失败', imgNameList[index])
        baseList.push('error')
        preload(arr, index + 1)
      }
      img.src = arr[index]
    }
  }
  preload(arr)
}
